<template>
  <div class="marketing-container">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="活动名称">
          <el-input v-model="searchForm.name" placeholder="请输入活动名称" clearable />
        </el-form-item>
        <el-form-item label="活动类型">
          <el-select v-model="searchForm.type" placeholder="请选择活动类型" clearable>
            <el-option label="满减优惠" value="discount" />
            <el-option label="返现活动" value="rebate" />
            <el-option label="赠品活动" value="gift" />
            <el-option label="优惠券" value="coupon" />
            <el-option label="限时活动" value="limited" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增活动</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 活动列表 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        border
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
        stripe
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="活动名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="type" label="活动类型" width="120">
          <template #default="scope">
            <el-tag :type="getActivityTypeTag(scope.row.type)">
              {{ getActivityTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="活动时间" width="300">
          <template #default="scope">
            {{ scope.row.startTime }} 至 {{ scope.row.endTime }}
          </template>
        </el-table-column>
        <el-table-column prop="participants" label="参与人数" width="100" align="right" />
        <el-table-column prop="budget" label="预算金额" width="120" align="right">
          <template #default="scope">
            {{ formatAmount(scope.row.budget) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="活动状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
              <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-dropdown>
                <el-button link type="primary">
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleUpdateStatus(scope.row, 'ongoing')">开始活动</el-dropdown-item>
                    <el-dropdown-item @click="handleUpdateStatus(scope.row, 'finished')">结束活动</el-dropdown-item>
                    <el-dropdown-item @click="handleUpdateStatus(scope.row, 'cancelled')">取消活动</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="650px"
      destroy-on-close
      @closed="resetForm"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择活动类型" style="width: 100%">
            <el-option label="满减优惠" value="discount" />
            <el-option label="返现活动" value="rebate" />
            <el-option label="赠品活动" value="gift" />
            <el-option label="优惠券" value="coupon" />
            <el-option label="限时活动" value="limited" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间" prop="timeRange" required>
          <el-date-picker
            v-model="formData.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="预算金额" prop="budget">
          <el-input-number
            v-model="formData.budget"
            :min="0"
            :precision="2"
            :step="1000"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="目标人数" prop="targetParticipants">
          <el-input-number
            v-model="formData.targetParticipants"
            :min="0"
            :precision="0"
            :step="100"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="关联产品" prop="products">
          <el-select
            v-model="formData.products"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择关联产品"
            style="width: 100%"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入活动描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="营销活动详情"
      width="700px"
      destroy-on-close
    >
      <el-skeleton :loading="detailLoading" animated>
        <template #default>
          <div class="detail-container">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="活动名称">{{ activityDetail.name }}</el-descriptions-item>
              <el-descriptions-item label="活动类型">{{ getActivityTypeName(activityDetail.type) }}</el-descriptions-item>
              <el-descriptions-item label="开始时间">{{ formatDateTime(activityDetail.startTime) }}</el-descriptions-item>
              <el-descriptions-item label="结束时间">{{ formatDateTime(activityDetail.endTime) }}</el-descriptions-item>
              <el-descriptions-item label="活动预算">{{ activityDetail.budget || '0' }} 元</el-descriptions-item>
              <el-descriptions-item label="目标参与人数">{{ activityDetail.targetParticipants || '不限' }}</el-descriptions-item>
              <el-descriptions-item label="当前参与人数">{{ activityDetail.participants || '0' }}</el-descriptions-item>
              <el-descriptions-item label="转化金额">{{ activityDetail.conversionAmount || '0' }} 元</el-descriptions-item>
              <el-descriptions-item label="活动状态">
                <el-tag :type="getStatusType(activityDetail.status)">{{ getStatusName(activityDetail.status) }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ formatDateTime(activityDetail.createTime) }}</el-descriptions-item>
              <el-descriptions-item label="创建人">{{ activityDetail.creator }}</el-descriptions-item>
              <el-descriptions-item label="活动描述" :span="2">{{ activityDetail.description || '暂无描述' }}</el-descriptions-item>
              <el-descriptions-item label="活动规则" :span="2">{{ activityDetail.rules || '暂无规则' }}</el-descriptions-item>
            </el-descriptions>

            <div class="detail-section" v-if="activityDetail.products && activityDetail.products.length > 0">
              <h4>关联产品</h4>
              <el-table :data="activityDetail.products" border stripe style="width: 100%">
                <el-table-column prop="name" label="产品名称" min-width="120" />
                <el-table-column prop="type" label="产品类型" width="100">
                  <template #default="{ row }">
                    {{ getProductTypeName(row.type) }}
                  </template>
                </el-table-column>
                <el-table-column prop="rate" label="产品利率" width="100">
                  <template #default="{ row }">
                    {{ row.rate || '--' }}%
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <div class="detail-section">
              <h4>活动数据</h4>
              <el-tabs>
                <el-tab-pane label="参与度">
                  <div class="chart-placeholder">参与度数据图表</div>
                </el-tab-pane>
                <el-tab-pane label="转化率">
                  <div class="chart-placeholder">转化率数据图表</div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </template>
        <template #template>
          <div style="padding: 20px">
            <el-skeleton-item variant="text" style="width: 30%" />
            <el-divider />
            <el-skeleton-item variant="text" style="margin-bottom: 10px" />
            <el-skeleton-item variant="text" style="width: 90%; margin-bottom: 10px" />
            <el-skeleton-item variant="text" style="width: 80%; margin-bottom: 10px" />
            <el-skeleton-item variant="text" style="width: 85%; margin-bottom: 10px" />
            <el-skeleton-item variant="text" style="width: 70%; margin-bottom: 10px" />
            <el-skeleton-item variant="text" style="width: 75%; margin-bottom: 10px" />
          </div>
        </template>
      </el-skeleton>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { marketingApi, productApi } from '@/api/product'

// 数据统计
const statistics = ref({
  totalActivities: 0,
  activityRate: 0,
  participants: 0,
  participantRate: 0,
  conversionAmount: 0,
  conversionRate: 0,
  roi: 0,
  roiRate: 0
})

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  dateRange: [],
  pageNum: 1,
  pageSize: 10
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const submitLoading = ref(false)
const formData = reactive({
  name: '',
  type: '',
  timeRange: [],
  budget: 0,
  targetParticipants: 0,
  products: [],
  description: ''
})

// 产品选项
const productOptions = ref([])

// 详情对话框
const detailVisible = ref(false)
const activityDetail = ref({})
const detailLoading = ref(false)

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  timeRange: [
    { required: true, message: '请选择活动时间', trigger: 'change' }
  ],
  budget: [
    { required: true, message: '请输入预算金额', trigger: 'blur' }
  ],
  targetParticipants: [
    { required: true, message: '请输入目标人数', trigger: 'blur' }
  ],
  products: [
    { required: true, message: '请选择关联产品', trigger: 'change' }
  ]
}

// 获取活动类型标签类型
const getActivityTypeTag = (type) => {
  const map = {
    discount: 'primary',
    rebate: 'success',
    gift: 'warning',
    coupon: 'info',
    limited: 'danger',
    other: 'info'
  }
  return map[type] || 'info'
}

// 获取活动类型名称
const getActivityTypeName = (type) => {
  const map = {
    discount: '满减优惠',
    rebate: '返现活动',
    gift: '赠品活动',
    coupon: '优惠券',
    limited: '限时活动',
    other: '其他活动'
  }
  return map[type] || type || '--'
}

// 获取状态标签类型
const getStatusType = (status) => {
  const map = {
    planning: 'info',
    ongoing: 'primary',
    finished: 'success',
    cancelled: 'danger'
  }
  return map[status] || ''
}

// 获取状态名称
const getStatusName = (status) => {
  const map = {
    planning: '筹备中',
    ongoing: '进行中',
    finished: '已结束',
    cancelled: '已取消'
  }
  return map[status] || status || '--'
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '--'
  const date = new Date(dateStr)
  const isValid = !isNaN(date.getTime())
  if (!isValid) return dateStr
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 获取产品类型名称
const getProductTypeName = (type) => {
  const typeMap = {
    loan: '贷款产品',
    deposit: '存款产品',
    fund: '基金产品',
    wealth: '理财产品',
    insurance: '保险产品'
  }
  return typeMap[type] || type || '--'
}

// 格式化金额
const formatAmount = (amount) => {
  return amount ? `¥${Number(amount).toLocaleString()}` : '¥0'
}

// 获取统计数据
const getStatistics = async () => {
  // try {
  //   const res = await marketingApi.getStatistics()
  //   console.log('获取统计数据响应:', res)
    
  //   let statsData = null
    
  //   // 处理嵌套数据结构
  //   if (res.data) {
  //     if (res.data.data) {
  //       if (res.data.data.data) {
  //         // 三层嵌套
  //         statsData = res.data.data.data
  //       } else {
  //         // 两层嵌套
  //         statsData = res.data.data
  //       }
  //     } else {
  //       // 一层嵌套
  //       statsData = res.data
  //     }
  //   }
    
  //   if (statsData) {
  //     statistics.value = {
  //       totalActivities: statsData.totalActivities || 0,
  //       activityRate: statsData.activityRate || 0,
  //       participants: statsData.participants || 0,
  //       participantRate: statsData.participantRate || 0,
  //       conversionAmount: statsData.conversionAmount || 0,
  //       conversionRate: statsData.conversionRate || 0,
  //       roi: statsData.roi || 0,
  //       roiRate: statsData.roiRate || 0
  //     }
  //   } else {
  //     console.warn('未能识别统计数据结构:', res)
  //   }
    
  //   console.log('处理后的统计数据:', statistics.value)
  // } catch (error) {
  //   console.error('获取统计数据失败:', error)
  //   ElMessage.error('获取统计数据失败，请稍后重试')
  // }
}

// 获取产品选项
const getProductOptions = async () => {
  try {
    const res = await productApi.getList({ status: 'active', pageSize: 100 })
    console.log('获取产品选项响应:', res)
    
    let productsData = []
    
    // 处理嵌套数据结构
    if (res.data) {
      if (res.data.data) {
        if (res.data.data.data && res.data.data.data.rows) {
          // 三层嵌套
          productsData = res.data.data.data.rows
        } else if (res.data.data.rows) {
          // 两层嵌套
          productsData = res.data.data.rows
        } else if (Array.isArray(res.data.data)) {
          // 两层嵌套，但直接是数组
          productsData = res.data.data
        }
      } else if (res.data.rows) {
        // 一层嵌套
        productsData = res.data.rows
      } else if (Array.isArray(res.data)) {
        // 一层嵌套，但直接是数组
        productsData = res.data
      }
    }
    
    if (productsData.length > 0) {
      productOptions.value = productsData.map(item => ({
        id: item.id,
        name: item.name
      }))
    } else {
      console.warn('未能识别产品数据结构:', res)
      productOptions.value = []
    }
    
    console.log('处理后的产品选项:', productOptions.value)
  } catch (error) {
    console.error('获取产品选项失败:', error)
    ElMessage.error('获取产品选项失败，请稍后重试')
    productOptions.value = []
  }
}

// 获取活动列表
const getMarketingList = async () => {
  loading.value = true;
  
  // 创建请求数据对象的副本
  const requestData = {
    page: searchForm.pageNum,
    pageSize: searchForm.pageSize,
    name: searchForm.name,
    type: searchForm.type
  };

  // 格式化日期（与提交表单使用相同的格式化函数）
  const formatDate = (date) => {
    if (!date) return '';
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');
    const seconds = String(d.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };

  // 处理日期范围
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    requestData.startTime = formatDate(searchForm.dateRange[0]);
    requestData.endTime = formatDate(searchForm.dateRange[1]);
  }
  
  try {
    const res = await marketingApi.getList(requestData);
    console.log('获取营销活动数据响应:', res);
    
    // 处理嵌套数据结构
    let listData = [];
    let totalCount = 0;
    
    if (res.data) {
      if (res.data.data) {
        if (res.data.data.data) {
          // 三层嵌套 - 实际API返回格式
          listData = res.data.data.data.rows || [];
          totalCount = res.data.data.data.total || 0;
        } else if (res.data.data.rows) {
          // 两层嵌套
          listData = res.data.data.rows || [];
          totalCount = res.data.data.total || 0;
        } else if (Array.isArray(res.data.data)) {
          // 两层嵌套，但直接是数组
          listData = res.data.data;
          totalCount = res.data.total || listData.length || 0;
        }
      } else if (res.data.rows) {
        // 一层嵌套
        listData = res.data.rows;
        totalCount = res.data.total || 0;
      } else if (Array.isArray(res.data)) {
        // 一层嵌套，但直接是数组
        listData = res.data;
        totalCount = listData.length;
      }
    }
    
    // 如果没有获取到数据，可能是其他结构
    if (listData.length === 0) {
      console.warn('未能识别API返回的数据结构:', res);
    }
    
    tableData.value = listData.map(item => {
      // 确保必要字段存在
      return {
        id: item.id || '',
        name: item.name || '',
        type: item.type || '',
        status: item.status || '',
        startTime: item.startTime || '',
        endTime: item.endTime || '',
        budget: item.budget || 0,
        participants: item.participants || 0,
        conversionAmount: item.conversionAmount || 0,
        description: item.description || '',
        rules: item.rules || '',
        creator: item.creator || '',
        createTime: item.createTime || '',
        updater: item.updater || '',
        updateTime: item.updateTime || ''
      };
    });
    
    total.value = totalCount;
    console.log('处理后的活动列表数据:', tableData.value);
    
  } catch (error) {
    console.error('获取营销活动列表失败:', error);
    ElMessage.error('获取营销活动列表失败，请稍后重试');
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 查询
const handleSearch = () => {
  searchForm.pageNum = 1
  getMarketingList()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.type = ''
  searchForm.dateRange = []
  handleSearch()
}

// 新增
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '新增活动'
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  resetForm()
  
  // 先填入表格行数据
  formData.id = row.id
  formData.name = row.name || ''
  formData.type = row.type || ''
  formData.budget = row.budget || 0
  formData.description = row.description || ''
  formData.timeRange = [row.startTime, row.endTime]
  
  try {
    dialogTitle.value = '编辑活动'
    dialogVisible.value = true
    submitLoading.value = true
    
    // 获取完整详情数据
    const res = await marketingApi.getDetail(row.id)
    console.log('编辑活动获取详情响应:', res)
    
    let detailData = null
    
    // 处理嵌套数据结构
    if (res.data) {
      if (res.data.data) {
        if (res.data.data.data) {
          // 三层嵌套
          detailData = res.data.data.data
        } else {
          // 两层嵌套
          detailData = res.data.data
        }
      } else {
        // 一层嵌套
        detailData = res.data
      }
    }
    
    if (detailData) {
      // 更新表单数据
      formData.name = detailData.name || formData.name
      formData.type = detailData.type || formData.type
      formData.budget = detailData.budget || formData.budget
      formData.targetParticipants = detailData.targetParticipants || 0
      formData.description = detailData.description || formData.description
      formData.rules = detailData.rules || ''
      formData.status = detailData.status || row.status
      
      // 处理活动时间范围
      if (detailData.startTime && detailData.endTime) {
        formData.timeRange = [detailData.startTime, detailData.endTime]
      }
      
      // 处理关联产品
      if (detailData.products && Array.isArray(detailData.products)) {
        formData.products = detailData.products.map(product => product.id || product)
      } else {
        formData.products = []
      }
    }
    
    console.log('编辑活动表单数据:', formData)
  } catch (error) {
    console.error('获取活动详情失败:', error)
    ElMessage.error('获取活动详情失败，请稍后重试')
  } finally {
    submitLoading.value = false
  }
}

// 更新活动状态
const handleUpdateStatus = (row, status) => {
  const statusMap = {
    planning: '筹备中',
    ongoing: '进行中',
    finished: '已结束',
    cancelled: '已取消'
  };
  
  const statusText = statusMap[status] || status;
  
  ElMessageBox.confirm(`确定要将活动状态更改为"${statusText}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const updateData = {
        id: row.id,
        status: status
      };
      
      console.log('更新活动状态数据:', updateData);
      
      const res = await marketingApi.updateStatus(updateData);
      console.log('更新活动状态响应:', res);
      
      // 处理响应
      if (res.code === 200 || res.status === 200 || (res.data && res.data.code === 200)) {
        ElMessage.success(`活动状态已更新为"${statusText}"`);
        getMarketingList(); // 刷新列表
      } else {
        const errorMsg = res.msg || res.message || '操作失败';
        ElMessage.error(errorMsg);
      }
    } catch (error) {
      console.error('更新活动状态失败:', error);
      ElMessage.error('更新活动状态失败，请稍后重试');
    }
  }).catch(() => {
    // 用户取消操作
  });
}

// 查看详情
const handleView = async (row) => {
  detailVisible.value = true
  detailLoading.value = true
  
  try {
    // 初始化详情对象
    activityDetail.value = {
      id: row.id,
      name: row.name || '',
      type: row.type || '',
      status: row.status || '',
      startTime: row.startTime || '',
      endTime: row.endTime || '',
      budget: row.budget || 0,
      targetParticipants: row.targetParticipants || 0,
      participants: row.participants || 0,
      conversionAmount: row.conversionAmount || 0,
      description: row.description || '',
      rules: row.rules || '',
      creator: row.creator || '',
      createTime: row.createTime || '',
      products: []
    }
    
    // 获取详情数据
    const res = await marketingApi.getDetail(row.id)
    console.log('活动详情响应:', res)
    
    let detailData = null
    
    // 处理嵌套数据结构
    if (res.data) {
      if (res.data.data) {
        if (res.data.data.data) {
          // 三层嵌套 - 实际API返回格式
          detailData = res.data.data.data
        } else {
          // 两层嵌套
          detailData = res.data.data
        }
      } else {
        // 一层嵌套
        detailData = res.data
      }
    }
    
    if (detailData) {
      // 更新详情数据
      activityDetail.value = {
        ...activityDetail.value,
        ...detailData,
        // 确保必要字段存在
        name: detailData.name || activityDetail.value.name,
        type: detailData.type || activityDetail.value.type,
        status: detailData.status || activityDetail.value.status,
        startTime: detailData.startTime || activityDetail.value.startTime,
        endTime: detailData.endTime || activityDetail.value.endTime,
        budget: detailData.budget || activityDetail.value.budget,
        targetParticipants: detailData.targetParticipants || activityDetail.value.targetParticipants,
        participants: detailData.participants || activityDetail.value.participants,
        conversionAmount: detailData.conversionAmount || activityDetail.value.conversionAmount,
        description: detailData.description || activityDetail.value.description,
        rules: detailData.rules || activityDetail.value.rules,
        creator: detailData.creator || activityDetail.value.creator,
        createTime: detailData.createTime || activityDetail.value.createTime,
        // 处理产品数据，确保其为数组
        products: Array.isArray(detailData.products) ? detailData.products : []
      }
    }
    
    console.log('处理后的活动详情数据:', activityDetail.value)
  } catch (error) {
    console.error('获取活动详情失败:', error)
    ElMessage.error('获取活动详情失败，请稍后重试')
  } finally {
    detailLoading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      
      try {
        // 格式化时间，移除时区信息
        const formatDate = (date) => {
          if (!date) return '';
          const d = new Date(date);
          const year = d.getFullYear();
          const month = String(d.getMonth() + 1).padStart(2, '0');
          const day = String(d.getDate()).padStart(2, '0');
          const hours = String(d.getHours()).padStart(2, '0');
          const minutes = String(d.getMinutes()).padStart(2, '0');
          const seconds = String(d.getSeconds()).padStart(2, '0');
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        };

        // 格式化提交数据
        const submitData = {
          name: formData.name,
          type: formData.type,
          startTime: formatDate(formData.timeRange[0]),
          endTime: formatDate(formData.timeRange[1]),
          budget: Number(formData.budget),
          targetParticipants: Number(formData.targetParticipants),
          description: formData.description,
          products: formData.products,
          status: dialogTitle.value.includes('新增') ? 'planning' : formData.status
        }
        
        // 如果是编辑模式，添加id
        if (formData.id) {
          submitData.id = formData.id
        }
        
        console.log('提交的活动数据:', submitData)
        
        let res
        if (formData.id) {
          // 编辑
          res = await marketingApi.updateMarketing(submitData)
        } else {
          // 新增
          res = await marketingApi.addMarketing(submitData)
        }
        
        console.log('提交活动响应:', res)
        
        if (res.code === 200 || res.status === 200 || (res.data && res.data.code === 200)) {
          ElMessage.success(dialogTitle.value.includes('新增') ? '添加成功' : '更新成功')
          dialogVisible.value = false
          getMarketingList() // 刷新列表
        } else {
          const errorMsg = res.msg || res.message || '操作失败'
          ElMessage.error(errorMsg)
        }
      } catch (error) {
        console.error('提交活动表单失败:', error)
        ElMessage.error('提交失败，请稍后重试')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: undefined,
    name: '',
    type: '',
    timeRange: [],
    budget: 0,
    targetParticipants: 0,
    products: [],
    description: ''
  })
}

// 分页
const handleSizeChange = (val) => {
  searchForm.pageSize = val
  getMarketingList()
}

const handleCurrentChange = (val) => {
  searchForm.pageNum = val
  getMarketingList()
}

// 初始化
onMounted(() => {
  getStatistics()
  getProductOptions()
  getMarketingList()
})
</script>

<style scoped>
.marketing-container {
  padding: 20px;
}

.statistics {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-body {
  text-align: center;
}

.value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.rate {
  font-size: 14px;
}
.rate.up {
  color: #67C23A;
}
.rate.down {
  color: #F56C6C;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.charts {
  margin-top: 20px;
}

.placeholder-chart {
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 样式区域 */
.dashboard {
  margin-bottom: 20px;
}

.data-card {
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 0 20px;
}

.detail-container {
  padding: 10px;
}

.detail-section {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.detail-section h4 {
  margin: 0 0 10px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
}

.chart-placeholder {
  height: 200px;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
  border-radius: 4px;
}

@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
  }
}
</style> 